package com.tonghe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tonghe.constants.SystemConstants;
import com.tonghe.domain.ResponseResult;
import com.tonghe.domain.entity.Comment;
import com.tonghe.domain.entity.User;
import com.tonghe.enums.AppHttpCodeEnum;
import com.tonghe.exception.SystemException;
import com.tonghe.mapper.CommentMapper;
import com.tonghe.service.CommentService;
import com.tonghe.service.UserService;
import com.tonghe.utils.BeanCopyUtils;
import com.tonghe.vo.CommentVo;
import com.tonghe.vo.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 评论表(Comment)表服务实现类
 *
 * @author tonghe
 * @since 2022-03-11 19:44:19
 */
@Service("commentService")
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    private UserService userService;

      /**
      * @description: 根据类型(link / article)、 文章id 获取评论
      * @param： [commentType, articleId, pageNum, pageSize]
      * @author: TongHe
      * @date: 2022/3/17 17:53
      */
    @Override
    public ResponseResult commentList(String commentType, Long articleId, Integer pageNum, Integer pageSize) {
        // region queryWrapper
        // 查询对应文章得根评论
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        // articleId判断
        queryWrapper.eq(SystemConstants.ARTICLE_COMMENT.equals(commentType), Comment::getArticleId, articleId);
        // 根评论 rootId -1
        queryWrapper.eq(Comment::getRootId, -1);
        // 评论类型
        queryWrapper.eq(Comment::getType, commentType);
        // endregion
        // 分页查询
        Page<Comment> page = new Page(pageNum, pageSize);
        page(page, queryWrapper);
        // 封装
        List<CommentVo> commentVoList = toCommentVoList(page.getRecords());

        // 查询所有根评论对应得字评论集合，并且赋值给对应得属性
        for(CommentVo commentVo : commentVoList){
            // 查询对应得子评论
            List<CommentVo> children = getChildren(commentVo.getId());
            // 赋值
            commentVo.setChildren(children);
        }
        return ResponseResult.okResult(new PageVo(commentVoList, page.getTotal()));
    }

   /**
   * @description: 添加评论
   * @param： [comment]
   * @author: TongHe
   * @date: 2022/3/17 17:53
   */
    @Override
    public ResponseResult addComment(Comment comment) {
        // 判断内容是否为空（前后端双校验）
        if( !StringUtils.hasText(comment.getContent())){
            // 抛出异常
            throw new SystemException(AppHttpCodeEnum.CONTENT_NOT_NULL);
        }

        // 插入评论，有关自动插入
        return save(comment)?ResponseResult.okResult():ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
    }
    /**
    * @description: 代码服用，提取根评论的子评论
    * @param： [id]
    * @return： java.util.List<com.tonghe.vo.CommentVo>
    * @author: TongHe
    * @date: 2022/3/17 17:53
    */
    private List<CommentVo> getChildren(Long id) {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getRootId, id);
        queryWrapper.orderByAsc(Comment::getCreateTime);
        List<Comment> comments = list(queryWrapper);
        List<CommentVo> commentVos = toCommentVoList(comments);


        return commentVos;
    }
    /**
    * @description:
    * @param： [list]
    * @return： java.util.List<com.tonghe.vo.CommentVo>
    * @author: TongHe
    * @date: 2022/3/17 17:53
    */
    private List<CommentVo> toCommentVoList(List<Comment> list){
        List<CommentVo> commentVos = BeanCopyUtils.copyBeanList(list, CommentVo.class);
        // 遍历vo集合
        for(CommentVo commentVo : commentVos){
            // 通过createBy查询用户得昵称并赋值
            User user = userService.getById(commentVo.getCreateBy());
            String nickName = user.getNickName();
            String avatar = user.getAvatar();
            commentVo.setUsername(nickName);
            commentVo.setAvatar(avatar);
            // 通过toCommentUserList查询用户得昵称并赋值
            if(commentVo.getToCommentUserId() != -1){
                String toCommentUserName = userService.getById(commentVo.getToCommentUserId()).getNickName();
                commentVo.setToCommentUserName(toCommentUserName);
            }
        }
        return commentVos;
    }
}
